# -*- coding:utf-8 -*-

import time
import threading

class DictQueue:
    def __init__(self,saveTm=300):#second
        self._dictQueue = {}
        self._savetime  = saveTm
        
    def put(self,key,data):
        """ """
        tm = time.time()
        saveData = _saveData(tm,data);
        self._clear(tm)
        if self._dictQueue.has_key(key):
            self._dictQueue[key].append(saveData)
        else:
            self._dictQueue[key] = [saveData]
            
    def get(self,key,timeout=0):
        """ """
        times = 0
        while times<timeout or timeout==0:
            if self._dictQueue.has_key(key) and len(self._dictQueue[key]):
                saveData =  self._dictQueue[key].pop(0);
                return saveData.data;
            time.sleep(1);
            times += 1    
        return None
        
    def _clear(self,tm):
        if self._savetime<=0:
            return
        for i in self._dictQueue.keys():
            for j in self._dictQueue[i]:
                if j.tm + self._savetime < tm:
                    self._dictQueue[i].remove(j);
    def qsize(self):
        """ """
        return len(self._dictQueue);
        
    def has_key(self,key):
        """ """
        return self._dictQueue.has_key(key);
        
class _saveData:
    """ """
    def __init__(self,tm,data):
        self.tm     =   tm
        self.data   =   data
        
if __name__ == "__main__":
    s = DictQueue()
    s.put(1,2)
    s.put(3,4);
    print s.get(2,2)
